package cn.itcast.hello;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
/**
 * @author KTL
 * @version V1.0
 * @Package cn.itcast.hello
 * @date 2021/2/21 0021 10:31
 * @Copyright © 2015-04-29  One for each, and two for each
 *      演示：flink-dataset-api-实现wordcount
 */
public class WordCount {
    public static void main(String[] args) throws Exception {
     ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
     DataSet<String> lines = env.fromElements("itcast hadoop spark", "itcast hadoop saprk", "itcast hadoop", "itcast");
        DataSet<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String values, Collector<String> out) throws Exception {
                String[] arr = values.split(" ");
                for (String word : arr) {
                    out.collect(word);
                }
            }
        });
         MapOperator<String, Tuple2<String, Integer>> wrodAndOne = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });
         UnsortedGrouping<Tuple2<String, Integer>> grouded = wrodAndOne.groupBy(0);
         AggregateOperator<Tuple2<String, Integer>> result = grouded.sum(1);
        result.print();
    }
}
